//
//  ViewController.swift
//  VideoTrim
//
//  Created by LevyGG on 2019/9/17.
//  Copyright © 2019 LevyGG. All rights reserved.
//

import UIKit
import Photos

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
    }

    @IBAction func push(_ sender: Any) {
        let path = Bundle.main.path(forResource: "test", ofType:"mp4")!
        let editController = UIVideoEditorController()
        if UIVideoEditorController.canEditVideo(atPath: path) {
            editController.videoPath = path
            editController.delegate = self
            editController.videoMaximumDuration = 300 // 设置最长可截取的视频长度，单位：秒
            present(editController, animated:true)
        }else{
            let alertController = UIAlertController(title: "该视频无法编辑", message: nil, preferredStyle: .alert)
            let defaultAction = UIAlertAction(title: "确定", style: .default, handler: nil)
            alertController.addAction(defaultAction)
            self.present(alertController, animated: true, completion: nil)
        }
        
    }
    
}

extension ViewController: UIVideoEditorControllerDelegate,UINavigationControllerDelegate {
    func videoEditorController(_ editor: UIVideoEditorController,
       didSaveEditedVideoToPath editedVideoPath: String) {
        print(editedVideoPath)
        guard let url = URL.init(string: editedVideoPath) else { return  }
        
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
        }) { saved, error in
            if saved {
                DispatchQueue.main.async {
                    let alertController = UIAlertController(title: "视频保存成功保存到相册", message: nil, preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "确定", style: .default, handler: nil)
                    alertController.addAction(defaultAction)
                    self.present(alertController, animated: true, completion: nil)
                }
            }
        }
        
       dismiss(animated:true)
    }

    func videoEditorControllerDidCancel(_ editor: UIVideoEditorController) {
       dismiss(animated:true)
    }

    func videoEditorController(_ editor: UIVideoEditorController,
               didFailWithError error: Error) {
       print("an error occurred: \(error.localizedDescription)")
       dismiss(animated:true)
    }
}
